package com.javabi.common.lang;

/**
 * A class for displaying percentages easily and in a human-readable format.
 */
public class Percent {

	private static int getMultiplier(int precision) {
		int multiplier = 1;
		for (int i = 0; i < precision; i++) {
			multiplier *= 10;
		}
		return multiplier;
	}

	private static int getDigits(long value) {
		if (value < 0) {
			throw new IllegalArgumentException("value=" + value);
		}
		int digits = 1;
		int divisor = 10;
		while (true) {
			if (value / divisor == 0) {
				break;
			}
			digits++;
			divisor *= 10;
		}
		return digits;
	}

	private final long percent;
	private final int precision;
	private final int multiplier;

	public Percent(long dividend, long divisor, int precision) {
		if (dividend < 0) {
			throw new IllegalArgumentException("dividend=" + dividend);
		}
		if (divisor < 1) {
			throw new IllegalArgumentException("divisor=" + divisor);
		}
		if (precision < 0) {
			throw new IllegalArgumentException("precision=" + precision);
		}
		this.precision = precision;
		this.multiplier = getMultiplier(precision);
		this.percent = (dividend * 100 * multiplier) / divisor;
	}

	public long longValue() {
		return percent;
	}

	@Override
	public String toString() {
		if (precision == 0) {
			return percent + "%";
		}
		long whole = percent / multiplier;
		long decimal = percent % multiplier;
		StringBuilder text = new StringBuilder();
		text.append(whole).append('.');
		int digits = getDigits(decimal);
		while (digits < precision) {
			digits++;
			text.append('0');
		}
		text.append(decimal).append('%');
		return text.toString();
	}
}
